package Core 
{	
	import com.junkbyte.console.Cc;
	import Common.CommonMessage;
	import Common.Constants;
	import Common.ErrorMessage;
	import Common.TextMessage;
	import Common.ViewerSubstrate;
	import flash.display.LoaderInfo;
	
	import Albums.AlbumEvent;
	import Albums.AlbumIcon;
	import Albums.AlbumsManager;	
	import Albums.AlbumsPage;
	import Common.Messages;
	import Fonts.CalibriEmbed;
	import Network.XMLErrorEvent;
	import Network.XMLLoader;	
		
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.display.StageAlign;
	import flash.events.ContextMenuEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.BlurFilter;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	import flash.system.Security;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	import flash.utils.Dictionary;
	import fl.containers.ScrollPane;
	/**
	 * Main uploader class
	 * @author Serg de Adelantado
	 */
	public class Main extends Sprite
	{
		private var FInterface:InterfaceContainer;
		//Buttons
		private var FBrowse:IconButton;		
		private var FUpdate:IconButton;		
		private var FViewer:ImagesViewer;
		private var FSubstrate:ViewerSubstrate;		
		private var FScroller:ScrollPane;
		private var FXMLInfo:TextField;
		private var FImageViewer:ImageViewer;
		private var FIconsToltip:Tooltip;
		private var FAlbums:AlbumsPage;
		private var FMessages:Messages;
		private var FAlbumsManager:AlbumsManager;
		//local file browsing
		private var FSelector:FileReferenceList;
		private var FImagesFileFilter:FileFilter;
		//remote files
		private var FXMLLoader:XMLLoader;
		//filter for images viewer fade effect
		private var FBlur:BlurFilter;
		//Buttons collecton
		private var FButtons:Dictionary;
		private var FButtonsCollection:Vector.<IconButton>;
		
		public function Main()
		{
			super.stage.scaleMode = StageScaleMode.NO_SCALE;
			super.stage.align = StageAlign.TOP_LEFT;
			stage.addEventListener(Event.RESIZE, OnStageResize);			
			FButtonsCollection = new Vector.<IconButton>;			
			FSelector = new FileReferenceList();			
			FSelector.addEventListener(Event.SELECT, OnImagesSelect);			
			FImagesFileFilter = new FileFilter('Image File', '*.jpg;*.png;*.bmp;*.gif;*.tga');
			FBlur = new BlurFilter(5, 5, 3);			
			FXMLLoader = new XMLLoader();			
			SetupConsole();			
			Security.loadPolicyFile('http://www.dikar-sochi.ru/crossdomain.xml');
			Security.loadPolicyFile('http://62.76.190.98/crossdomain.xml');
			Cc.logch('Security', 'Policy file loaded');			
			SetupContextMenu();
			SetupInterface();
		}
		
		private function SetupInterface()
		{
			FInterface = getChildByName('WorkInterface') as InterfaceContainer;			
			FButtons = new Dictionary();			
			FBrowse = AddIcon('Browse', FolderIcon);
			FBrowse.Caption = 'Добавить фото';
			FUpdate = AddIcon('Update', UpdateIcon);
			FUpdate.Caption = 'Сохранить фото';			
		
			FBrowse.Text = 'Выбор файлов' + '\n' + 
			"<font color='" + '#666666' + "'>" + 'Обзор локальных файлов для загрузки на сервер' + "</font>";
						
			FUpdate.Text = 'Опубликовать' + '\n' + 
			"<font color='" + '#666666' + "'>" + 'Локальные файлы будут загружены на сервер' + "</font>";
						
			FBrowse.addEventListener(MouseEvent.MOUSE_DOWN, OnBrowseButton);
			FUpdate.addEventListener(MouseEvent.MOUSE_DOWN, OnUpdateButton);
				
			FViewer = new ImagesViewer();			
			FViewer.XMLS = FXMLLoader;
			FViewer.Buttons = FButtons;
			FViewer.AllButtonsEnabled = false;
			FBrowse.Enabled = true;
			
			FScroller = GetUIElement('Scroller') as ScrollPane;
			FScroller.source = FViewer;
			FSubstrate = new ViewerSubstrate(FScroller);
			
			FImageViewer = new ImageViewer();
			addChild(FImageViewer);
			FImageViewer.addEventListener(MouseEvent.MOUSE_DOWN, OnImageViewerClick);
			
			FAlbums = new AlbumsPage();
			FAlbums.XMLS = FXMLLoader;
			FAlbums.Viewer = FViewer;
			FAlbums.Root = this;
			FInterface.addChild(FAlbums);
			FInterface.swapChildren(FAlbums, FBrowse);			
			FViewer.Albums = FAlbums;
			FViewer.Root = this;
			FAlbums.addEventListener(AlbumEvent.ALBUM_SELECTED, OnAlbumSelected);
			
			FScroller.visible = false;
			FImageViewer.visible = false;
			FAlbums.visible = false;
			
			FXMLInfo = new TextField();
			addChild(FXMLInfo);			
			var vFormat:TextFormat = new TextFormat();			
			vFormat.align = TextFormatAlign.CENTER;
			vFormat.font = new CalibriEmbed().fontName;
			vFormat.size = 14;
			FXMLInfo.autoSize = TextFieldAutoSize.NONE;
			FXMLInfo.selectable = false;
			FXMLInfo.defaultTextFormat = vFormat;
			FXMLInfo.text = 'Загрузка информации...';
			
			FMessages = new Messages();
			addChild(FMessages);
			
			FAlbumsManager = new AlbumsManager();			
			FAlbumsManager.Root = this;
			FInterface.addChild(FAlbumsManager);
			
			OnStageResize(null);					
			var vID:String;			
			vID = LoaderInfo(root.loaderInfo).parameters['obj_id'];
			trace(vID);
			if (!vID)
				vID = '-1';
			trace(vID);
			FXMLLoader.Load(vID);
			FXMLLoader.addEventListener(Event.COMPLETE, OnXMLLoaded);
			FXMLLoader.addEventListener(XMLErrorEvent.LOGIN_ERROR, OnLoginError);
			FXMLLoader.addEventListener(XMLErrorEvent.PARSER_ERROR, OnParserError);
		}		
		
		private function OnStageResize(e:Event):void 
		{			
			FUpdate.x = stage.stageWidth - FUpdate.FullWidth - 5;			
			
			FMessages.SetSize(stage.stageWidth, stage.stageHeight);
			
			FXMLInfo.width = stage.stageWidth;
			FXMLInfo.x = 0;
			FXMLInfo.y = (stage.stageHeight - FXMLInfo.textHeight) / 2;
			
			FAlbums.SetSize(stage.stageWidth - 10, AlbumIcon.SIZE);
			FAlbums.x = 5;
			FAlbums.y = 43;
			
			var vManagerHeight:int;
			FAlbumsManager.SetSize(stage.stageWidth - 10, 0);
			vManagerHeight = FAlbumsManager.height * int(FAlbumsManager.visible)			
			FAlbumsManager.x = 5;
			FAlbumsManager.y = FAlbums.y + FAlbums.height;			
			
			FScroller.x = 5;			
			FScroller.width = stage.stageWidth - 10;
			FScroller.height = stage.stageHeight - (FAlbums.y + FAlbums.height) - vManagerHeight - 5;
			FScroller.y = FAlbums.y + FAlbums.height + vManagerHeight;						
			FViewer.Width = FScroller.width - FScroller.verticalScrollBar.width;
			FScroller.update();
			
			FSubstrate.SetSize(FScroller.width, FScroller.height);
			FSubstrate.x = FScroller.x;
			FSubstrate.y = FScroller.y;
			
			FImageViewer.y = FImageViewer.x = 0;
			FImageViewer.Resize(stage.stageWidth, stage.stageHeight);			
		}
		
		private function OnImagesSelect(e:Event):void 
		{
			FImageViewer.Close();	
			UnBlur();			
			for each(var vImage:ImageContainer in FViewer.LoadFromList(FSelector))			
				RegisterForViewer(vImage);
		}		
		
		public function RegisterForViewer(AImage:ImageContainer):void		
		{
			AImage.addEventListener(MouseEvent.DOUBLE_CLICK, OnImageClick);	
		}
		
		private function OnImageClick(e:MouseEvent):void 
		{
			FImageViewer.Image = ImageContainer(e.target);
			if (FImageViewer.visible)
				Blur();
		}
		
		public function Blur()
		{
			FInterface.filters = [FBlur];			
			FAlbums.filters = [FBlur];
		}
		
		public function UnBlur()
		{
			FInterface.filters = [];
			FAlbums.filters = [];
		}
		
		private function OnImageViewerClick(e:MouseEvent):void 
		{			
			UnBlur();
		}
				
		private function OnAlbumSelected(e:AlbumEvent):void 
		{
			FAlbumsManager.visible = e.Album.AlbumRoom.ID != FXMLLoader.MainID;
			OnStageResize(null);
		}		
		
		private function OnLoginError(e:XMLErrorEvent):void 
		{
			var vMessage:ErrorMessage = new ErrorMessage();
			MessagesCore.Show(vMessage);
			vMessage.Header = 'Ошибка подключения';
			vMessage.Description = 'Возможно, Вы не авторизированы, или истек срок действия сессии.' + '\n' +
				'Нажмите на сообщение для перехода к странице авторизации.';
			vMessage.addEventListener(MouseEvent.MOUSE_DOWN, OnErrorMessage)
			vMessage.useHandCursor = vMessage.buttonMode = true;
		}
		
		private function OnParserError(e:XMLErrorEvent):void 
		{
			var vMessage:ErrorMessage = new ErrorMessage(350, 128);			
			MessagesCore.Show(vMessage);
			vMessage.Header = 'Ошибка подключения';
			vMessage.Description = 'Парсер базы данных ' + '\n"' + Constants.MAIN_XML + '"\n' + ' не найден. ' +
			'Пожалуйста, сообщите администрации об ошибке.';			
		}
		
		private function OnErrorMessage(e:MouseEvent):void 
		{
			navigateToURL(new URLRequest(Constants.AUTH_SCRIPT), '_self');
		}
		
		private function OnXMLLoaded(e:Event):void 
		{
			FScroller.visible = true;			
			FAlbums.visible = true;
			FXMLInfo.visible = false;
		}
		
		private function AddIcon(AName:String, ADefaultIcon:Class):IconButton
		{
			var vResult:IconButton = GetUIElement(AName + 'Button') as IconButton;
			vResult.AddIcon(ADefaultIcon);
			FButtons[AName] = vResult;
			vResult.Icon = ADefaultIcon;
			FButtonsCollection.push(vResult);
			return vResult;
		}
		
		private function SetupConsole():void
		{
			Cc.config.style.backgroundAlpha = 0.8;			
			Cc.startOnStage(this, '`');
			Cc.width = stage.stageWidth;
			Cc.fpsMonitor = true;
			Cc.memoryMonitor = true;
			Cc.commandLine = true;
			Cc.config.commandLineAllowed = true;
			Cc.config.style.topMenu = false;			
			Cc.visible = false;
		}
		
		private function SetupContextMenu():void
		{
			var vMenu:ContextMenu = new ContextMenu();
			var vAutor:ContextMenuItem = new ContextMenuItem('Профиль автора на free-lance.ru');			
			vAutor.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, OnAutorClick);
			vMenu.hideBuiltInItems();
			vMenu.customItems.push(vAutor);
			contextMenu = vMenu;
			function OnAutorClick(e:ContextMenuEvent):void 
			{
				navigateToURL(new URLRequest('http://www.free-lance.ru/users/C4Grey/'), '_blank');
			}
		}
			
		private function GetUIElement(AName:String):DisplayObject
		{
			return FInterface.getChildByName(AName);
		}
		
		private function OnBrowseButton(e:MouseEvent):void 
		{
			FSelector.browse([FImagesFileFilter]);			
		}
		
		private function OnUpdateButton(e:MouseEvent):void 
		{
			FViewer.Sync();
		}
		
		public function get Buttons():Dictionary
		{
			return FButtons;
		}
		
		public function get MessagesCore():Messages
		{
			return FMessages;
		}
		
		public function get AlbumsTabs():AlbumsPage
		{
			return FAlbums;
		}
		
		public function get AlbumsTabsManager():AlbumsManager
		{
			return FAlbumsManager;
		}
	}
}